<?php
class Tourismorder extends CS_Controller
{
    public function _init()
    {
        $this->load->helper(array('common'));
        $this->load->library('pagination');
        $this->load->model('tourism_order_model','tourism_order');
        $this->load->model('tourism_order_product_model','tourism_order_product');
        $this->load->model('tourism_order_refund_model','tourism_order_refund');
        $this->load->model('tourism_goods_base_model','tourism_goods_base');
        $this->load->model('tourism_goods_image_model','tourism_goods_image');
        $this->load->model('express_model', 'express');
        $this->load->model('express_record_model', 'express_record');
        $this->load->model('user_model','user');
    }

    /**
     *商品详情列表
     */
    public function grid($pg = 1)
    {
        $getData = $this->input->get();
        $getData['seller_uid'] = $this->uid;
        $page_num = 15;
        $num = ($pg - 1) * $page_num;
        $config['first_url'] = base_url('tourismorder/grid').$this->pageGetParam($this->input->get());
        $config['suffix']    = $this->pageGetParam($this->input->get());
        $config['base_url']  = base_url('tourismorder/grid');
        $config['total_rows'] = $this->tourism_order->total($getData);
        $config['uri_segment'] = 3;
        $this->pagination->initialize($config);
        $data['pg_link']   = $this->pagination->create_links();
        $list = $this->tourism_order->page_list($page_num, $num, $getData);
        if ($list->num_rows() > 0) {
            foreach ($list->result() as $item) {
                $ids[] = $item->order_id;
            }
            $params['ids'] = $ids;
        } else {
            $params['ids'] = array();
        }
        if (isset($getData['excel']) && $getData['excel']== 'excel') {
            if ($list->num_rows() <= 0) {
                $this->error('tourismorder/grid', '' , '找不到订单相关信息！');
            }
            $downGoods = $this->tourism_order->page_list_down($params); //取特定字段
            $this->excelExport($downGoods);
        } else {
            $goods = $this->tourism_order->page_lists($params);
            $data['list'] = $this->decrypt($goods);
            $data['all_rows']  = $config['total_rows'];
            $data['pg_now']    = $pg;
            $data['pg_num'] = $page_num;
            $data['orderStatus'] = array('3'=>'已付款', '4'=>'已发货', '5'=>'已收货', '6'=>'已评价', '1'=>'已取消','2'=>'未付款');
            $data['statusTotal'] = $this->tourism_order->orderStatusTotal($getData, true);
            if (isset($getData['order_status'])) {
                unset($getData['order_status']);
            }
            if (isset($getData['seller_uid'])) {
                unset($getData['seller_uid']);
            }
            $data['urlparams'] = $this->pageGetParam($getData);
            $this->load->view('tourismorder/grid', $data);
        }
    }
    
     /**
     *导出的商品订单
     *@param unknown $goods
     */
    public function excelExport($downGoods)
    {
        if ($downGoods->num_rows() <= 0) {
            $this->error('tourismorder/grid', '' , '找不到订单相关信息！');
        }
        $arrayOrder = $downGoods->result_array();
        $arrayOrderDown = array();
        foreach ($arrayOrder as $key=>$item){
            
            $receive = json_decode($item['detail'],true);
            $arrayOrderDown[$key]['order_sn'] = $item['order_sn'];
            $arrayOrderDown[$key]['alias_name'] = $item['alias_name'];
            $arrayOrderDown[$key]['goods_name'] = $item['goods_name'];
            $arrayOrderDown[$key]['attribute_value'] = $item['attribute_value'];
            $arrayOrderDown[$key]['number'] = $item['refund_num'];
            $arrayOrderDown[$key]['supply_price'] = $item['supply_price'];
            $arrayOrderDown[$key]['receiver_name'] = $receive['receiver_name'];
            $arrayOrderDown[$key]['province_name'] = $receive['province_name'];
            $arrayOrderDown[$key]['detailed'] = $receive['detailed'];
            $arrayOrderDown[$key]['code'] = $receive['code'];
            $arrayOrderDown[$key]['tel'] = $receive['tel'];
            $arrayOrderDown[$key]['message'] = $item['message'];
        }
        array_unshift($arrayOrderDown, array('订单号','购买者','商品名称','规格属性','数量','供应价','收货人','省份','详细地址','邮政编码','收货电话','客户留言'));
        $this->load->library('excel');
        $this->excel->addArray($arrayOrderDown);
        $this->excel->generateXML(date('Ymd').'商品订单');
    }
    
    /**
     * 处理数据
     * @param unknown $data
     * @return multitype:|Ambigous <multitype:, unknown>
     */
    public function decrypt($data)
    {
    
        $argc = array();
        if (empty($data)) {
            return array();
        }
        foreach ($data->result() as $key => $item) {

            $argc[$item->order_id]['user_name'] = $item->user_name;
            $argc[$item->order_id]['order_sn'] = $item->order_sn;
            $argc[$item->order_id]['order_id'] = $item->order_id;
            $argc[$item->order_id]['created_at'] = $item->created_at;
            $argc[$item->order_id]['order_price'] = $item->order_price;
            $argc[$item->order_id]['actual_price'] = $item->actual_price;
            $argc[$item->order_id]['order_pay_total'] = $item->order_pay_total;
            $argc[$item->order_id]['transport_cost'] = $item->transport_cost;
            $argc[$item->order_id]['order_status'] = $item->order_status;
            $argc[$item->order_id]['actually_price'][] = array(
                'supplier_price' => $item->supply_price,
                'number'         => $item->number,
                'refund_num'     => $item->refund_num,
            );
            $argc[$item->order_id]['shop_goods'][] = $item;
        }
        return $argc;
    }
    
    /**
     * 订单详情
     * @param unknown $order_id
     */
    public function info($order_id)
    {
        $result = $this->tourism_order->findByOrderId($order_id);
        if ($result->num_rows() <= 0) {
            $this->error('tourismorder/grid', '', '找不到订单相关信息！');
        }
        $order = $result->row();
        $data['logistics'] = $this->express_record->findByNu($order->logistics);
        $data['logisticsAll'] = $this->express->findAll();
        $data['orderInfo'] = $order;
        $data['orderProductInfo'] = $this->tourism_order_product->getProductByOrderId($order_id);
        $this->load->view('tourismorder/info', $data);
    }
    
    /**
     * 修改运费价格
     */
    public function modifyTransport()
    {
        $order_id = $this->input->post('order_id');
        $transport_cost = $this->input->post('transport_cost');
        $result = $this->tourism_order->findByOrderId($order_id);
        if ($result->num_rows() <= 0) {
            echo json_encode(array(
                'status' => false,
                'msg'    => '网络错误，订单信息不对',
            ));exit;
        }
        $orderInfo = $result->row();
        if ($transport_cost < 0) {
            echo json_encode(array(
                'status' => false,
                'msg'    => '修改价格必须要大于等于零',
            ));exit;
        }
        $is_mobile = $this->tourism_order->modifyTransport($order_id, $transport_cost);
        if ($is_mobile) {
            echo json_encode(array(
                    'status'   => true,
            ));exit;
        } else {
            echo json_encode(array(
                'status' => false,
                'msg'    => '运费价格修改失败',
            ));exit;
        }
    }
    
    /**
     * 取消订单
     * @param unknown $order_id
     */
    public function undo($order_id)
    {
        $result = $this->tourism_order->findByOrderId($order_id);
        if ($result->num_rows() <= 0) {
            $this->error('tourismorder/grid', '', '找不到订单相关信息！');
        }
        $backUrl = $this->input->get('backUrl');
        if (!$backUrl) {
            $backUrl = site_url('tourismorder/grid');
        }
        
        $this->db->trans_start();
        $resultId = $this->tourism_order->UndoNotPayOrder(array('order_id'=>$order_id));
        $this->db->trans_complete();

        if ($this->db->trans_status() === TRUE && $resultId) {
            $this->success($backUrl, '', '取消订单成功');
        } else {
            $this->error($backUrl, '', '取消订单失败');
        }
    }
    
    public function logistics()
    {
        $this->load->view('tourismorder/logistics');
    }
    
     /**
     * 发货成功与失败
     */
    public function logisticsPost()
    {
        $order_id = $this->input->post('logistics_order_id');
        $result = $this->tourism_order->findByOrderId($order_id);
        if ($result->num_rows() <= 0) {
            $this->error('tourismorder/info', $order_id, '当前订单错误');
        }
        $orderInfo = $result->row();
        $userResult = $this->user->findByUid($orderInfo->payer_uid);
        if ( $userResult->num_rows() <= 0){
            $this->error('tourismorder/info', $order_id, '当前订单支付人不存在');
        }
        $userInfo = $userResult->row(0);
        $postData = $this->input->post();
        $postData['order_id'] = $this->input->post('logistics_order_id');
        
        //判断是否存在退款信息 如果存在未处理的订单信息暂时无法发货
//         $refundNum = $this->tourism_order_refund->isRefundByOrderId($order_id);
//         if ($refundNum) {
//             $this->error('tourismorder/info', $order_id, '此订单存在未处理的退货或换货的信息，请先处理退货或换货操作');
//         }
        if ($orderInfo->order_state != 2 || !(in_array($orderInfo->order_status,array(3,4))) ) { //当前订单为已付款状态才可发货，但是填错了物流单号可以修改
            $this->error('tourismorder/info', $order_id, '当前状态不可操作。');
        }
        $this->db->trans_begin();
        
        $result = $this->expressSend();
        if($result != 100)
        {
            $this->error('tourismorder/info', $order_id, $result);
        }
        $isUpdate = $this->tourism_order->sendTourismOrder($postData);
        
        $deliveryResult = $this->tourism_order->findDeliveryByOrderId($order_id);
        if ($deliveryResult->num_rows() <= 0) {
            $this->error('tourismorder/info', $order_id, '当前订单错误');
        }
        $deliveryInfo = $deliveryResult->row(0);
        $phone = empty($userInfo->mobile_phone) ? $deliveryInfo->tel : $userInfo->mobile_phone;
        if ($this->db->trans_status() === FALSE  || !$isUpdate) {
            $this->db->trans_rollback();
            $this->error('tourismorder/info', $order_id, '发货失败');
        } else {
            $this->db->trans_commit();
            //您预订的商品:'. $deliveryInfo->goods_name .'(订单号:'.$deliveryInfo->order_sn.'),已经于'.date('Y-m-d').'发货, 运单号:'.$deliveryInfo->logistics.' ,请您在签收时务必注意检查商品不存在外观破损、商品不全等问题后，再确认收货！
            $this->sendCommonSmsInfo($phone, 'SMS_136394703', ['goods_name' => $deliveryInfo->goods_name, 'order_sn' => $deliveryInfo->order_sn, 'date' => date('Y-m-d'), 'logistics' => $deliveryInfo->logistics]);
            $this->success('tourismorder/info', $order_id, '您已发货成功');
        }
    }

    public function expressSend()
    {
        $company = trim($this->input->post('logistics_company'));
        $number = trim($this->input->post('logistics'));

        if (!validExpressNu($number)) {
            return '快递单号只能是5位以上的数字、字母组成';
        }
        $expressRecord = $this->express_record->findByNu($number);
        if ($expressRecord->num_rows() > 0) {
            return 100;
        }

        $this->load->library('express', null, 'expressLibrary');
        $result = $this->expressLibrary->send($company, $number);
        if (!$result) {
            return '发货失败('.$this->expressLibrary->getMessage().')';
        }

        $express = $this->express->findByName($company)->row(); //查询快递名称
        $data = [
            'name'    => $express->name,
            'company' => $company,
            'number'  => $number,
            'ischeck' => -1,
            'state'   => -1,
            'context' => '',
            'create_at' => date('Y-m-d H:i:s')
        ];
        $resultId = $this->express_record->insert($data);
        if (!$result || !$resultId) {
            return '发货失败(数据插入失败)';
        }
        return 100;
    }
}